package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserIdFavors;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.service.IUserIdFavorsService;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.util.RidesKey;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class StrategyStatisVORedisServiceImpl implements IStrategyStatisVORedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IUserIdFavorsService userIdFavorsService;
    @Autowired
    private MongoTemplate template;

    @Override
    public void viewnumIncrease(String sid, int num){
        StrategyStatisVO vo = getStrategyStatisVO(sid);
        vo.setViewnum(vo.getViewnum() + num);
        this.setStrategyStatisVO(vo);
    }


    public StrategyStatisVO getStrategyStatisVO(String sid){
        String join = RidesKey.STRATEGY_STATIS_STRATEGYSTATISVO.join(sid);

        StrategyStatisVO vo = null;

        if (!redisTemplate.hasKey(join)){

            vo = new StrategyStatisVO();

            Strategy strategy = strategyService.findById(sid);
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());

        }else {
            String strategyStatisVO = redisTemplate.opsForValue().get(join);
            vo = JSON.parseObject(strategyStatisVO, StrategyStatisVO.class);
        }
        return vo;
    }

    @Override
    public void setStrategyStatisVO(StrategyStatisVO vo){
        String key = RidesKey.STRATEGY_STATIS_STRATEGYSTATISVO.join(vo.getStrategyId());
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
    }

    @Override
    public boolean isStrategyVoExist(String id) {
        String key = RidesKey.STRATEGY_STATIS_STRATEGYSTATISVO.join(id);
        if (redisTemplate.hasKey(key)){
            return true;
        }
        return false;
    }

    @Override
    public List<StrategyStatisVO> findAllStrategyStatisVO() {
        String patten = RidesKey.STRATEGY_STATIS_STRATEGYSTATISVO.join("*");
        ArrayList<StrategyStatisVO> vos = new ArrayList<>();
        Set<String> keys = redisTemplate.keys(patten);
        if (keys != null && keys.size() > 0){
            for (String key : keys) {
                String vo = redisTemplate.opsForValue().get(key);
                vos.add(JSON.parseObject(vo,StrategyStatisVO.class));
            }
        }
        return vos;
    }

    @Override
    public void setMongodb(List<StrategyStatisVO> strategyStatisVOS) {
        for (StrategyStatisVO strategyStatisVO : strategyStatisVOS) {
            /*Strategy strategy = strategyService.findById(strategyStatisVO.getStrategyId());
            strategy.setViewnum(strategyStatisVO.getViewnum());
            strategy.setReplynum(strategyStatisVO.getReplynum());
            strategy.setSharenum(strategyStatisVO.getSharenum());
            strategy.setThumbsupnum(strategyStatisVO.getThumbsupnum());
            strategy.setFavornum(strategyStatisVO.getFavornum());
            strategyService.update(strategy);*/

            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(strategyStatisVO.getStrategyId()));

            Update update = new Update();
            update.set("viewnum", strategyStatisVO.getViewnum());
            update.set("replynum",strategyStatisVO.getReplynum() );
            update.set("sharenum", strategyStatisVO.getSharenum());
            update.set("thumbsupnum", strategyStatisVO.getThumbsupnum());
            update.set("favornum", strategyStatisVO.getFavornum());

            template.updateMulti(query,update ,Strategy.class );
        }
    }


    @Override
    public StrategyStatisVO statisVo(String sid) {

       /* String join = RedisKeys.STRATEGY_STATIS_STRATEGYSTATISVO.join(sid);
        String stategyStatisVo = redisTemplate.opsForValue().get(join);


        if (!StringUtils.hasLength(stategyStatisVo)){

            StrategyStatisVO strategyStatisVO = new StrategyStatisVO();
            Strategy strategy = strategyService.findById(sid);
            BeanUtils.copyProperties(strategy,strategyStatisVO);
            strategyStatisVO.setViewnum(strategyStatisVO.getViewnum() + 1);
            redisTemplate.opsForValue().set(join, JSON.toJSONString(strategyStatisVO), Consts.VERIFY_CODE_VAI_TIME*60L, TimeUnit.SECONDS);

            return strategyStatisVO;
        }else {
            StrategyStatisVO strategyStatisVO = JSON.parseObject(stategyStatisVo, StrategyStatisVO.class);
            strategyStatisVO.setViewnum(strategyStatisVO.getViewnum() + 1);
            redisTemplate.opsForValue().set(join, JSON.toJSONString(strategyStatisVO), Consts.VERIFY_CODE_VAI_TIME*60L, TimeUnit.SECONDS);
            return strategyStatisVO;
        }*/

        String join = RidesKey.STRATEGY_STATIS_STRATEGYSTATISVO.join(sid);

        StrategyStatisVO vo = null;

        if (!redisTemplate.hasKey(join)){

            vo = new StrategyStatisVO();

            Strategy strategy = strategyService.findById(sid);
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());

        }else {
            String strategyStatisVO = redisTemplate.opsForValue().get(join);
            vo = JSON.parseObject(strategyStatisVO, StrategyStatisVO.class);
        }

        return vo;
    }

    @Override
    public void replynumIncrease(String strategyId, int num) {
        StrategyStatisVO vo = getStrategyStatisVO(strategyId);
        vo.setReplynum(vo.getReplynum() + num);
        this.setStrategyStatisVO(vo);
    }

    @Override
    public boolean favor(String sid, String uid) {
        //先查询是否有当前这篇攻略的收藏的list集合(里面存放对应已经点赞的用户)
        String key = RidesKey.STRATEGY_USER_ID.join(uid);
        StrategyStatisVO strategyStatisVO = this.getStrategyStatisVO(sid);

       UserIdFavors userIdFavors = new UserIdFavors();
        userIdFavors.setFavors(new ArrayList<>());

        if (redisTemplate.hasKey(key)){

            userIdFavors = JSON.parseObject(redisTemplate.opsForValue().get(key), UserIdFavors.class);
            List<String> objects = userIdFavors.getFavors();
            if (objects.contains(sid)){
                objects.remove(sid);
                //把当前用户id移除出集合
                //对应点赞数-1
                strategyStatisVO.setFavornum(strategyStatisVO.getFavornum() - 1);
                //把数据更新回去
                redisTemplate.opsForValue().set(key, JSON.toJSONString(userIdFavors));
                this.setStrategyStatisVO(strategyStatisVO);
                return false;
            }
            objects.add(sid);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(userIdFavors));
            strategyStatisVO.setFavornum(strategyStatisVO.getFavornum() + 1);
            this.setStrategyStatisVO(strategyStatisVO);

        }else {

            UserIdFavors favors = userIdFavorsService.findByUsid(uid);
            List<String> favors1 = favors.getFavors();
            if (favors1.contains(sid)){
                favors1.remove(sid);
                //把当前用户id移除出集合
                //对应点赞数-1
                strategyStatisVO.setFavornum(strategyStatisVO.getFavornum() - 1);
                //把数据更新回去
                redisTemplate.opsForValue().set(key, JSON.toJSONString(favors));
                this.setStrategyStatisVO(strategyStatisVO);
                return false;
            }
            favors1.add(sid);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(favors));
            strategyStatisVO.setFavornum(strategyStatisVO.getFavornum() + 1);
            this.setStrategyStatisVO(strategyStatisVO);
        }


        return true;
    }

    @Override
    public List<String> getstrategyUserIds(String userId) {
        String key = RidesKey.STRATEGY_USER_ID.join(userId);
        UserIdFavors userIdFavors = new UserIdFavors();
        userIdFavors.setFavors(new ArrayList());
        if (redisTemplate.hasKey(key)){
            userIdFavors = JSON.parseObject(redisTemplate.opsForValue().get(key), UserIdFavors.class);
        }
        return userIdFavors.getFavors();
    }

    @Override
    public boolean strategyThumbup(String sid, String id) {
        String key = RidesKey.STRATEGY_THUMBUP.join(sid,id);
        if (redisTemplate.hasKey(key)){
            return false;
        }
        Date now = new Date();

        Date end = DateUtil.getEndDate(new Date());

        long dateBetween = DateUtil.getDateBetween(now, end);

        //设置一天点赞一次
        redisTemplate.opsForValue().set(key, sid, dateBetween, TimeUnit.SECONDS);

        StrategyStatisVO strategyStatisVO = this.getStrategyStatisVO(sid);
        strategyStatisVO.setThumbsupnum(strategyStatisVO.getThumbsupnum() + 1);
        this.setStrategyStatisVO(strategyStatisVO);

        return true;
    }



}

